package com.roger.springcloudGreenwich.connection;

import com.orbitz.consul.AgentClient;
import com.orbitz.consul.Consul;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created by admin on 2020/4/9.
 */
@Service
@Slf4j
public class ConsulClientPool {
    @Value("${consul.connectTimeout-millis}")
    private int connectTimeoutMillis;

    @Value("${consul.readTimeout-millis}")
    private int readTimeoutMillis;

    static ConcurrentMap<String, AgentClient> clientPool = new ConcurrentHashMap();

    public ConcurrentMap<String, AgentClient> getConsulClientMap(String host, int port, String aclToken){
        //this url is client host and port
        URL url;
        Consul consul;
        AgentClient agentClient;
        String key = host + ":" + port;
        try {
            if(!clientPool.containsKey(key)){
                url = new URL("http", host, port,"");
                consul = Consul.builder().withUrl(url).withAclToken(aclToken).
                        withConnectTimeoutMillis(connectTimeoutMillis).withReadTimeoutMillis(readTimeoutMillis).build();
                agentClient = consul.agentClient();
                clientPool.put(key, agentClient);
                log.info("put into pool");
            }
        }catch (Exception e){
            log.info("get consul error,message={}",e.getMessage());
        }
        return clientPool;
    }
}
